<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<title>敌人加个血条</title>
<script src="phaser.min.js">
</script>
</head>

<body>


<script>
var config={
	type:Phaser.AUTO,
	width:800,
	height:600,
	scene:{
		preload:preload,
		create:create,
		update:update
	},
	physics:{
		default:"arcade",
		arcade:{
			debug:false,
			gravity:{y:0}
		
		}
	}
};
var game;
var player;
var platforms;
var cursors;
var bullets;
var speed;
var lastFired = 0;
var space;
var player1;
var man1;
var skeletons = [];
var cam;
var glob;


var directions = {
    west: { offset: 0, x: -2, y: 0, opposite: 'east' },
    northWest: { offset: 32, x: -2, y: -1, opposite: 'southEast' },
    north: { offset: 64, x: 0, y: -2, opposite: 'south' },
    northEast: { offset: 96, x: 2, y: -1, opposite: 'southWest' },
    east: { offset: 128, x: 2, y: 0, opposite: 'west' },
    southEast: { offset: 160, x: 2, y: 1, opposite: 'northWest' },
    south: { offset: 192, x: 0, y: 2, opposite: 'north' },
    southWest: { offset: 224, x: -2, y: 1, opposite: 'northEast' }
};

var directionsString=["west","northWest","north","northEast","east","southEast","south","southWest"];

game=new Phaser.Game(config);

function  preload(){
	console.log("preload");
	
	this.load.image('bullet', 'images/star.png');
	this.load.spritesheet('man', 
		'images/h1.png',
		{ frameWidth: 80, frameHeight: 80 }
	);
	this.load.spritesheet('man1', 
		'images/h1.png',
		{ frameWidth: 80, frameHeight: 80 }
	);	
	
	this.load.image('walls_1x2', 'images/walls_1x2.png');
	
}
function  create(){
	glob=this;
	
	//本节关键代码
	var map = this.make.tilemap({  tileWidth: 32, tileHeight: 32,width: 80, height: 60 });	
	var tiles = map.addTilesetImage('walls_1x2', null, 32, 32);
	var layer = map.createBlankDynamicLayer('layer1', tiles);
	//0-7是图片的序列
	layer.randomize(0, 0, map.width, map.height, [ 0, 1, 2, 3, 4, 5, 6, 7 ]);
		
	cursors = this.input.keyboard.createCursorKeys();
	
	player=this.physics.add.sprite(0,0,"man");
	
	// Set world bounds
    this.physics.world.setBounds(0, 0, 2560, 1920);
	player.setCollideWorldBounds(true);
	//this.physics.add.collider(player, layer);
	//本节关键代码结束，设置镜头跟随的方法只是众多方法的一种，后期完善


	

    this.cameras.main.setBounds(0, 0, map.widthInPixels, map.heightInPixels);
    this.cameras.main.startFollow(player);
	//关键代码介绍

	
	
	
	
	//设置键和动作的关系
	this.anims.create({
		key: 'left',
		frames: this.anims.generateFrameNumbers('man', { start: 8, end: 15 }),
		frameRate: 15,
		repeat: -1
	});
	this.anims.create({
		key: 'turn',
		frames: [ { key: 'man', frame: 2 } ],
		frameRate: 20
	});
	this.anims.create({
		key: 'right',
		frames: this.anims.generateFrameNumbers('man', { start: 16, end: 23 }),
		frameRate: 15,
		repeat: -1
	});
	this.anims.create({
		key: 'up',
		frames: this.anims.generateFrameNumbers('man', { start: 24, end: 31 }),
		frameRate: 15,
		repeat: -1
	});
	this.anims.create({
		key: 'down',
		frames: this.anims.generateFrameNumbers('man', { start: 32, end: 39 }),
		frameRate: 15,
		repeat: -1
	});	
	
	//血条类
	class HealthBar {

		constructor (scene)
		{
			this.bar = new Phaser.GameObjects.Graphics(scene);
			this.scene=scene;
			this.value=100;
			this.bloodbarWidth=0;
			//宽度为76像素时，为100%；
			this.percentRatio=76/100;
		}
		draw (x,y)
		{
			this.bar.clear();
			
			//  BG
			this.bar.fillStyle(0x1E90FF);
			this.bar.fillRect(x-40, y-40, 80, 16);
			//health
			this.bar.fillStyle(0x00FFFF);
			this.bar.fillRect(x + 2-40, y + 2-40, this.value*this.percentRatio, 12);
			this.scene.add.existing(this.bar);
		}
		decrease (amount)
		{
			this.value -= amount;

			if (this.value < 0)
			{
				this.value = 0;
			}
			
			return (this.value === 0);
		}

	}
	//血条结束
	
	
	//所谓的敌人类,功能左右移动，随机生成敌人
	var Skeleton = new Phaser.Class({
		Extends: Phaser.GameObjects.Image,
		initialize:function skeleton(scene,x,y,direction,distance){
			//初始化敌人位置
		    this.startX = x;
            this.startY = y;
            this.distance = distance;
			this.f = 0;
			this.direction = directions[direction];
			
			Phaser.GameObjects.Image.call(this, scene, x, y, 'man1', this.direction.offset + this.f);
	
            this.depth = this.y + 64;
			this.scene=scene;
			//初始化血条
		    this.bloodbar=new HealthBar(this.scene);
			
		},
		update:function(){
			this.x += this.direction.x *0.15;

			if (this.direction.y !== 0)
			{
				this.y += this.direction.y * 0.16;
				this.depth = this.y + 64;
			}
			//来回游荡
			if (Phaser.Math.Distance.Between(this.startX, this.startY, this.x, this.y) >= this.distance)
			{
				
				this.direction = directions[this.direction.opposite];
				this.f = 0;
				this.frame = this.texture.get(this.direction.offset + this.f);
				this.startX = this.x;
				this.startY = this.y;
			}
			//更新血条位置
			this.bloodbar.draw(this.x,this.y);
		},
		damage:function(amount){
			if (this.bloodbar.decrease(amount))
			{
				return true;
			}else{
				return false;
			}
		}
	});
	
	
	skeletons.push(this.add.existing(new Skeleton(this, 200, 200, "west", 50)));
	skeletons.push(this.add.existing(new Skeleton(this, 400, 300, "south", 100)));
	
	
	//子弹类
	var Bullet = new Phaser.Class({

		Extends: Phaser.GameObjects.Image,

		initialize:function Bullet (scene)
		{
			Phaser.GameObjects.Image.call(this, scene, 0, 0, 'bullet');

			this.speed = Phaser.Math.GetSpeed(400, 1);
		},

		fire: function (x, y)
		{
			this.setPosition(x-50, y);

			this.setActive(true);
			this.setVisible(true);
		},

		update: function (time, delta)
		{
			//横向发送代码将this.y改为this.x
			this.x -= this.speed * delta;

			if (this.x < -50)
			{
				this.setActive(false);
				this.setVisible(false);
			}
		}

    });

    bullets = this.add.group({
        classType: Bullet,
        maxSize: 1,
        runChildUpdate: true
    });
	
	speed = Phaser.Math.GetSpeed(300, 1);
	space = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
	
	//定时
	this.timer = this.time.addEvent({ delay: Phaser.Math.Between(500, 1000), callback: function(){
		//数组里没有,todo 以后这里可以封装一个方法
		if(skeletons.length==0){
			var randomPosition = directionsString[Math.floor(Math.random() * directionsString.length)];
			var randomPosition2 = directionsString[Math.floor(Math.random() * directionsString.length)];
			var randomPosition3 = directionsString[Math.floor(Math.random() * directionsString.length)];
			
			skeletons.push(glob.add.existing(new Skeleton(glob, Phaser.Math.Between(0, 800), Phaser.Math.Between(0, 600), randomPosition, 150)));
			skeletons.push(glob.add.existing(new Skeleton(glob, Phaser.Math.Between(0, 800), Phaser.Math.Between(0, 600), randomPosition2, 50)));
			skeletons.push(glob.add.existing(new Skeleton(glob, Phaser.Math.Between(0, 800), Phaser.Math.Between(0, 600), randomPosition3, 200)));
		}
	},loop:true});
	


}



function update(time, delta){

	console.log(player.x);
console.log(player.y);
	skeletons.forEach(function (skeleton) {
		skeleton.update();
		var enemies = bullets.getChildren();
		var numEnemies = enemies.length;
		for (var i = 0; i < numEnemies; i++) {
			if (skeleton.active && Phaser.Geom.Intersects.RectangleToRectangle(skeleton.getBounds(), enemies[i].getBounds())) {
				//当血条为0时，返回的为真
				if(skeleton.damage(Phaser.Math.Between(1, 5))){
					 skeleton.visible=false;
					 skeleton.active=false;
					 //血条一起消失
					 skeleton.bloodbar.bar.visible=false;
					 //消灭一个从数组中pop一个
					 skeletons.pop();
					 break;
				}
				//只要碰到就消失
				enemies[i].visible=false;
				
			}
		}

	});
	


	if (cursors.left.isDown)
	{
		player.setVelocityX(-160);
		player.anims.play('left', true);		
		player.x -= speed * delta;
	}
	else if (cursors.right.isDown)
	{
		player.setVelocityX(160);
		player.anims.play('right', true);
		player.x += speed * delta;
	}else if(cursors.up.isDown){
		player.setVelocityY(-160);
		player.anims.play('up', true);
	}
	else if (cursors.down.isDown)
	{
		player.setVelocityY(160);
		player.anims.play('down', true);
	}else if( cursors.space.isDown && time > lastFired){
	    var bullet = bullets.get();
        if (bullet)
        {
            bullet.fire(player.x, player.y);

            lastFired = time + 50;
        }
	}
	else
	{
		player.setVelocityX(0);
		player.setVelocityY(0);
		player.anims.play('turn');
	}

}



</script>
</body>
</html>